import 'package:flutter/material.dart';
import 'package:sharing/resources/code_point.dart';
import 'package:sharing/resources/strings.dart';
import 'package:sharing/resources/styles.dart';
import 'package:sharing/resources/dimens.dart';
import 'package:sharing/resources/colors.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharing/model/history.dart';
import 'package:sqflite/sqflite.dart';
import 'dart:convert';
import 'package:sharing/utils/whole_apis.dart';
import "package:sharing/ui/widget/read_pdf_file_widget.dart";
import 'dart:io';
import 'package:sharing/model/book.dart';
import 'package:sharing/model/book.dart';
import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:sharing/utils/whole_apis.dart';
import 'package:sharing/net/ris_read_apis.dart';
import 'package:sharing/net/net_util.dart';
import 'package:path_provider/path_provider.dart';


class BookshelfPage extends StatefulWidget {
  BookshelfPage({Key key}) : super(key: key);

  _BookshelfPageState createState() => _BookshelfPageState();
}

class _BookshelfPageState extends State<BookshelfPage> {
  List<Book> _books = [];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Colors.white,
        title: Text(
          IdString.bookshelfTitle,
          style: AppStyles.pageTitleTextStyle,
        ),
        elevation: Dimensions.appBarElevation,
        actions: <Widget>[
          IconButton(
            icon: Text(
              "整理",
              style: TextStyle(fontSize: 16.0, color: AppColor.primary),
            ),
            onPressed: () {
              print("整理");
            },
          ),
        ],
      ),
      body: Container(
        margin: const EdgeInsets.symmetric(horizontal: 8.0),
        // 添加可以给 Column 的滚动条
        child: _body(context),
      ),
      // ),
    );
  }

  Widget _body(BuildContext context) {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 4.0),
      // child: SingleChildScrollView(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          _buildReading(context), // 正在阅读
          // 分割线....
          Container(
            margin: const EdgeInsets.only(top: 4.0, bottom: 4.0),
            height: 16.0,
            decoration: BoxDecoration(
                color: Colors.black12,
                borderRadius: BorderRadius.circular(4.0)),
          ),

          Expanded(
            child: Container(
              height: 0.0,
              child: _BookItem(books: _books,),
            ),
          ),
        ],
      ),
      // ),
    );
  }

  // 加载图书信息
  void _loadBookInfoHistories() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String authorization = await prefs.getString("authorization");
    NetUtil.originGet(WholeApis.hostName + RisReadApis.histories,
        Options(headers: {"authorization": authorization}),
            (Response response) {
          print("data ${response.data}");
          var code = response.data["code"];
          var message = response.data["message"];
          if (code == 200 && message != null) {
            _books.clear();
            _books = Book.fromJson(message);
            setState(() {});
          }
        });
  }
  @override
  void initState() {
   // _loadHistories();
     _loadBookInfoHistories();
  }

  LocalHistories localHistories;
  void _loadHistories () async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    String histories = await  prefs.getString("histories");
    print("histiry$histories");
    if (histories == null) {
      return ;
    }
    localHistories = LocalHistories.fromJson(json.decode(histories));
    print("obj ${localHistories.toJson()}");
    
  }
  // 正在阅读
  Widget _buildReading(BuildContext context) {
    return Card(
      margin: const EdgeInsets.symmetric(horizontal: 0.0, vertical: 0.0),
      //  color: Colors.red,

      child: Container(
        //  height: 180,
        height: 140.0,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(left: 4.0),
              padding: const EdgeInsets.only(
                  left: 4.0, right: 0.0, top: 4.0, bottom: 4.0),
              child: Card(
                elevation: 1.0,
                child: Image.network(
                  "https://www.googlewatchblog.de/wp-content/uploads/flutter.png",
                  width: 80.0,
                  height: 120.0,
                  fit: BoxFit.contain,
                ),
              ),
            ),

            // 书籍的信息
            // 书名
            // 作者
            // 阅读的进度
            Expanded(
              child: Container(
                padding:
                    const EdgeInsets.symmetric(horizontal: 8.0, vertical: 0.0),
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    //  显示书名
                    Text(
                      "这里显示的是书名",
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                      style: TextStyle(
                          fontWeight: FontWeight.normal,
                          fontSize: 20.0,
                          color: Color(0xff182740)),
                    ),

                    // 显示作者的名字
                    Container(
                      margin: const EdgeInsets.only(top: 4.0),
                      child: Text(
                        "这里显示作者的名字",
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                            fontSize: 14.0,
                            fontWeight: FontWeight.normal,
                            color: Color(0xffa6a7bb)),
                      ),
                    ),

                    // 显示底部的阅读的进度条....
                    Expanded(
                      child: Stack(
                        children: <Widget>[
                          Positioned(
                            bottom: 0,
                            child: Container(
                              margin: const EdgeInsets.only(bottom: 8.0),
                              child: Row(
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceEvenly,
                                crossAxisAlignment: CrossAxisAlignment.center,
                                children: <Widget>[
                                  Container(
                                    child: Text("阅读进度:"),
                                  ),
                                  Container(
                                    child: Text("8%"),
                                  ),
                                ],
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 书架
class _BookItem extends StatelessWidget {
  List<Book> books;
  _BookItem({@required this.books});

  // 加载图书文件 pdf
  Future<File> _createFileOfPdfUrl(Book book) async {
    String dir = (await getApplicationDocumentsDirectory()).path;
    // 分割文件名
    List<String> splits = book.saveName.split("/");
    String localPath = "$dir/${splits[splits.length - 1]}"; //
    print("path ${localPath}");
    var file = new File(localPath);

    bool exists = await file.existsSync();
    if (exists) {
      return file;
    } else {
      String url = "${WholeApis.hostName}/${book.saveName}";
      print("url $url");
      await Dio().download(url, file.path);
      var preferences = await SharedPreferences.getInstance();
      String  sp = preferences.getString("histories");
      LocalHistories histories = new LocalHistories();
      if (sp == null) {
        var history = LocalHistory(pdfPath: file.path,coverUrl: "",lastTime: DateTime.now(),process: 0);
        histories.localHistories = [];
        histories.localHistories.add(history);
        preferences.setString("histories",json.encode(histories.toJson()) );
      }else{
        var history = LocalHistory(pdfPath: file.path,coverUrl: "static/img/117547d5a84900f03db6e66b5273b3c0snapshot_1551485694336.png",lastTime: DateTime.now(),process: 0);
        histories = LocalHistories.fromJson(json.decode(sp));
        histories.localHistories.add(history);
        preferences.setString("histories",json.encode(histories.toJson()) );
      }
      return file;
    }
  }
  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
          crossAxisSpacing: 4.0,
          mainAxisSpacing: 4.0,
        ),
        itemCount: books == null ? 0 : books.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(
            onTap: () {
              print("GestureDetector ");
              Book book = books[index];
               _createFileOfPdfUrl(book)
                      .then((File file) {
                // 跳转到图书阅读页面
                Navigator.of(context).push(
                    MaterialPageRoute(
                        builder: (context) {
                          return ReadPdfFileWidget(
                            book: book,
                            pdfPath: file.path,
                          );
                        }));
              });

//              File file = new File(books[index].saveName);
//              Book book = new Book(name: books[index].name);
//              Navigator.of(context).push(
//                  MaterialPageRoute(
//                      builder: (context) {
//                        return ReadPdfFileWidget(
//                          book: book,
//                          pdfPath: file.path,
//                        );
//                      }));
            },
            child: Card(
              child: Container(
                height: 180,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: <Widget>[
                    // 显示书的封面
                    Expanded(
                      child: Container(
                        alignment: Alignment.center,
                        padding: const EdgeInsets.symmetric(
                            horizontal: 8.0, vertical: 4.0),
                        //  color: Colors.black38,
                        child: Image.network(
                          WholeApis.hostName +"/"+books[index].cover,
                          alignment: Alignment.center,
                          width: MediaQuery.of(context).size.width,
                          height: MediaQuery.of(context).size.height,
                          fit: BoxFit.contain,
                          //  fit: BoxFit.fill,
                        ),
                      ),
                    ),
                    // 书名
                    Container(
                      padding: const EdgeInsets.only(
                          left: 8.0, top: 4.0, bottom: 4.0, right: 4.0),
                      child: Text(
                        //"凡尔纳三部曲之<<神秘岛>>",
                        books[index].saveName,
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                        style: TextStyle(
                          fontSize: 14,
                          color: Color(0xff868d9e),
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
          );
        });
  }


}
